# koroFileHeader at Yungoal acer
# Create: 2022-06-28 15:59:59
# LastEdit: 2022-06-30 09:27:05
"""自定义过滤选项"""
__author__ = '749B'

from django.contrib import admin


class ResourceDynamicListFilter(admin.SimpleListFilter):
    """ResourcesAdmin list_filter 基类"""
    title = '订阅'
    parameter_name = 'subscription'
    values_list_keys = ('subscription__id', 'subscription__name')
    keep_get_keys = ['type', 'tenant_id', 'location', 'resource_group', 'subscription', 'ctime', 'uptime', 'del_time']

    def lookups(self, request, model_admin):
        # 只保留模型字段的过滤规则
        filter_dic = {}
        for k, v in request.GET.items():
            for keep_key in self.keep_get_keys:
                if k.startswith(keep_key):
                    v = True if v in ['true', 'True'] else v
                    v = False if v in ['false', 'False'] else v
                    filter_dic[k] = v
        # 根据get参数，过滤数据，提取显示的数据才有的选项
        qs = model_admin.get_queryset(request)
        if isinstance(self.values_list_keys, str):
            for lookup_title in qs.filter(**filter_dic).distinct().values_list(self.values_list_keys, flat=True):
                yield lookup_title, lookup_title
        else:
            for lookup_val, lookup_title in qs.filter(**filter_dic).distinct().values_list(*self.values_list_keys):
                yield lookup_val, lookup_title

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(**{self.parameter_name: self.value()})


class ResourceAuthListFilter(ResourceDynamicListFilter):
    title = '账号'
    parameter_name = 'subscription__auth__name'
    values_list_keys = ('subscription__auth__name', 'subscription__auth__display_name')


class ResourceSubscriptionListFilter(ResourceDynamicListFilter):
    title = '订阅'
    parameter_name = 'subscription'
    values_list_keys = ('subscription__id', 'subscription__name')


class ResourceGroupListFilter(ResourceDynamicListFilter):
    title = '资源组'
    parameter_name = 'resource_group'
    values_list_keys = 'resource_group'


class ResourceTypeListFilter(ResourceDynamicListFilter):
    title = '类型'
    parameter_name = 'type'
    values_list_keys = 'type'


class ResourceIsDeletedListFilter(admin.SimpleListFilter):
    """资源是否被删除"""

    title = "删除与否"
    parameter_name = 'is_deleted'

    def lookups(self, request, model_admin):
        return (
            ('yes', '已删除'),
            ('no', '未删除'),
            ('all', '全部'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            return queryset.filter(del_time__isnull=False)
        if self.value() == 'no':
            return queryset.filter(del_time__isnull=True)
        if self.value() == 'all':
            return queryset.all()
        # 如果没有筛选字段，也只返回未删除的资源。这样就实现了默认就只有未删除资源的需求
        return queryset.filter(del_time__isnull=True)

    def choices(self, changelist):
        """覆盖父类方法，修改默认选项的名称"""
        yield {
            "selected": self.value() is None,
            "query_string": changelist.get_query_string(remove=[self.parameter_name]),
            "display": "默认（已删除）",
        }
        for lookup, title in self.lookup_choices:
            yield {
                "selected": self.value() == str(lookup),
                "query_string": changelist.get_query_string(
                    {self.parameter_name: lookup}
                ),
                "display": title,
            }

